package com.xms.queryview.service;

import com.xms.core.exception.XmsException;
import com.xms.datacore.service.CreaterService;
import com.xms.queryview.entity.QueryView;
import com.xms.schema.entity.Attribute;
import com.xms.schema.entity.Entity;
import com.xms.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLException;
import java.util.Collection;
import java.util.List;

/**
 * <p>
 * QueryviewCreaterService
 * </p>
 *
 * @author migo
 * @since 2021/9/3
 */
@CacheConfig(cacheNames = "queryview", keyGenerator = "CacheKeyGenerator")
@Service
public class QueryViewCreaterService extends CreaterService<QueryView> implements IQueryViewCreaterService {
    private IDefaultQueryViewProvider _defaultQueryViewProvider;
    private IQueryViewDependency _queryViewDependency;

    @Autowired
    public void QueryviewCreaterService(IDefaultQueryViewProvider defaultQueryViewProvider,
                                        IQueryViewDependency queryViewDependency) {
        _defaultQueryViewProvider = defaultQueryViewProvider;
        _queryViewDependency = queryViewDependency;
    }

    @CacheEvict(allEntries = true, condition = "#result == true")
    @Transactional(rollbackFor=Exception.class)
    @Override
    public boolean createDefaultView(Entity entity, List<Attribute> attributes) throws XmsException, SQLException {
        QueryView defaultView = _defaultQueryViewProvider.get(entity, attributes);
        if (defaultView == null)
            return false;
        return this.create(defaultView);
    }

    @CacheEvict(allEntries = true, condition = "#result == true")
    @Transactional(rollbackFor=Exception.class)
    @Override
    public boolean create(QueryView entity) throws SQLException, XmsException {
        //压缩json
        entity.setFetchconfig(StringUtil.compress(entity.getFetchconfig()));
        entity.setLayoutconfig(StringUtil.compress(entity.getLayoutconfig()));
        entity.setAggregateconfig(StringUtil.compress(entity.getAggregateconfig()));
        boolean success = super.save(entity);
        if (success) {
            _queryViewDependency.create(entity);
        }
        return success;
    }

    @CacheEvict(allEntries = true, condition = "#result == true")
    @Transactional(rollbackFor=Exception.class)
    @Override
    public boolean createMany(Collection<QueryView> entityList) throws SQLException, XmsException {
        for (QueryView entity : entityList) {
            this.create(entity);
        }
        return true;
    }
}
